package com.orhon.smartcampus.modules.base.fetcher;

import com.orhon.smartcampus.basicComponents.Result;
import com.orhon.smartcampus.modules.base.dao.PeriodsDao;
import com.orhon.smartcampus.modules.base.entity.Periods;
import com.orhon.smartcampus.modules.base.gqlModel.GQLPageParam;
import com.orhon.smartcampus.modules.base.gqlModel.GQLPeriod;
import com.orhon.smartcampus.modules.base.mm.EnvArgsMapper;
import com.orhon.smartcampus.modules.base.mm.PeriodMapper;
import graphql.schema.DataFetcher;
import graphql.schema.DataFetchingEnvironment;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;

@Component
public class PeriodsFetcher implements DataFetcher {

    @Autowired
    PeriodsDao periodsDao;

    @Override
    public Object get(DataFetchingEnvironment env) throws Exception {        
        List<GQLPeriod> gqlPeriod = new ArrayList<>();


        GQLPageParam page = EnvArgsMapper.MAPPER.fromArgs(env);
        String hql = "from Periods where deleted_at = null ";
        List<Periods> list = periodsDao.find(hql,null,page.getPage(),page.getLimit());  

        for (Periods item : list) {
        	 GQLPeriod Period = PeriodMapper.MAPPER.toPeriods(item);
        	 gqlPeriod.add(Period);
        }
        
        Long total = 0L;
        if (env.getSelectionSet().contains("total")){
        	 total = periodsDao.getTotalCount(hql);
        }
        return Result.ok().put("data", gqlPeriod).put("total", total);
    }


}
